<script setup lang="ts">
import fs from "node:fs";
import { resolve } from "path";
import { onMounted, ref, watch } from "vue";
import { Button, ClButton } from "@chulei-ui/components";
import axios from "axios";
import { BigDecimal, DATE_TIME_FORMATTER } from "@chulei-ui/utils";
import dayjs from "dayjs";
import { ElLoading } from "@chulei-ui/element-plus";
import { useRouter } from "vue-router";
import {
  FORMATED_BLUEPRINTS_FILE,
  FORMATED_CATEGORY_FILE,
  FORMATED_PLANET_SCHEMATICS_FILE,
  FORMATED_TYPE_FILE,
  FORMATED_TYPE_MATERIALS_FILE,
  SDEFileUtils,
  SDE_CACHE_PATH,
  SDE_CHECKSUM_FILE,
  SDE_FILE,
  SDE_UN_PACK_DIR,
} from "../../sde";
import { FileUtils } from "../../utils";
import { Segment } from "~components/segment";
const sdeFile = ref();
const sdeStatus = ref<{ path?: string; downloaded?: boolean; time?: string; formated?: boolean }>({});
const router = useRouter();
const refreshSdeStatus = () => {
  sdeStatus.value = {
    path: SDE_FILE,
    downloaded: FileUtils.exist(SDE_FILE),
    time: FileUtils.attributes(SDE_FILE).birthtime,
    formated: FileUtils.exist(FORMATED_TYPE_FILE),
  };
};
watch(
  () => sdeFile.value,
  () => {
    fs.copyFileSync(sdeFile.value[0].raw.path, SDE_FILE);
    cleanCacheFiles();
    refreshSdeStatus();
  }
);
const sdeDownloadStatus = ref({
  error: undefined,
  percent: 0,
  loading: false,
});

const cleanCacheFiles = () => {
  fs.rmSync(resolve(SDE_CACHE_PATH, SDE_UN_PACK_DIR), { recursive: true, force: true });
  fs.rmSync(FORMATED_TYPE_MATERIALS_FILE, { force: true });
  fs.rmSync(FORMATED_TYPE_FILE, { force: true });
  fs.rmSync(FORMATED_CATEGORY_FILE, { force: true });
  fs.rmSync(FORMATED_BLUEPRINTS_FILE, { force: true });
  fs.rmSync(FORMATED_PLANET_SCHEMATICS_FILE, { force: true });
  fs.rmSync(SDE_CHECKSUM_FILE, { force: true });
};
const networkDownload = async () => {
  try {
    sdeDownloadStatus.value.loading = true;
    const { sdeLink } = await SDEFileUtils.fetchSDELinks();
    const response = await axios({
      method: "get",
      url: sdeLink!.link,
      responseType: "arraybuffer",
      onDownloadProgress(event) {
        sdeDownloadStatus.value.percent = BigDecimal.form(event.loaded)!
          .divide(event.total)
          .multiply(100)!
          .toFixed(2)
          ?.toNumber()!;
      },
    });
    cleanCacheFiles();
    FileUtils.saveFile(SDE_FILE, Buffer.from(response.data));
  } catch (e: any) {
    sdeDownloadStatus.value.error = e.message;
  } finally {
    sdeDownloadStatus.value.loading = false;
    refreshSdeStatus();
  }
};
/**
 * 重新格式化文件
 */
const sdeReformat = async () => {
  const loading = ElLoading.service({ text: "正在格式化", lock: true, background: "rgba(0, 0, 0, 0.7)" });
  try {
    await SDEFileUtils.unpack();
    await SDEFileUtils.reformat(loading);
  } finally {
    loading.close();
    refreshSdeStatus();
  }
};

onMounted(() => {
  refreshSdeStatus();
});
</script>

<template>
  <div class="space-y-4">
    <Segment>
      <template #header> 初始化 </template>
      <el-descriptions border :column="1">
        <el-descriptions-item label="缓存目录">{{ SDE_FILE }}</el-descriptions-item>
        <el-descriptions-item label="是否已下载">
          <span v-if="!sdeStatus.downloaded"> 否 </span>
          <span v-else> 是 </span>
          <el-progress v-if="sdeDownloadStatus.loading" :percentage="sdeDownloadStatus.percent" />
        </el-descriptions-item>
        <el-descriptions-item label="下载时间">{{
          sdeStatus.time ? dayjs(sdeStatus.time).format(DATE_TIME_FORMATTER) : ""
        }}</el-descriptions-item>
        <el-descriptions-item label="是否格式化">
          <div v-if="!sdeStatus.formated">否</div>
          <span v-else> 是 </span>
        </el-descriptions-item>
        <el-descriptions-item label="操作">
          <el-space>
            <cl-button
              v-if="!sdeDownloadStatus.loading"
              :type="sdeStatus.downloaded ? Button.Type.info : Button.Type.primary"
              @click="networkDownload"
              >云端加载</cl-button
            >
            <el-upload v-model:file-list="sdeFile" :limit="1" :show-file-list="false">
              <cl-button :type="sdeStatus.downloaded ? Button.Type.info : Button.Type.primary">本地加载</cl-button>
            </el-upload>

            <cl-button
              v-if="!sdeDownloadStatus.loading"
              :type="sdeStatus.formated ? Button.Type.info : Button.Type.primary"
              @click="sdeReformat"
            >
              格式化
            </cl-button>
          </el-space>
        </el-descriptions-item>
      </el-descriptions>
      <el-result v-if="sdeDownloadStatus.error" icon="error" :title="sdeFile" />
    </Segment>
    <cl-button
      v-if="sdeStatus.formated && sdeStatus.downloaded"
      class="w-full"
      :type="Button.Type.success"
      @click="() => router.push('/contracts')"
      >开始使用</cl-button
    >
  </div>
</template>

<style scoped lang="scss"></style>
